package com.legal.app.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.legal.app.domain.dto.PhoneLoginDTO;
import com.legal.app.domain.vo.UserInfoVO;
import com.legal.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.legal.common.annotation.Log;
import com.legal.common.core.controller.BaseController;
import com.legal.common.core.domain.AjaxResult;
import com.legal.common.enums.BusinessType;
import com.legal.app.domain.User;
import com.legal.app.service.IUserService;
import com.legal.common.utils.poi.ExcelUtil;
import com.legal.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 小程序用户Controller
 * 
 * @author Ale
 * @date 2025-05-30
 */
@RestController
@Api(tags = "小程序用户模块")
@RequestMapping("/app/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    /**
     * 查询小程序用户列表
     */
    @ApiOperation("小程序用户列表")
    @PreAuthorize("@ss.hasPermi('app:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(User user) {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 导出小程序用户列表
     */
    @ApiOperation("导出小程序用户列表")
    @PreAuthorize("@ss.hasPermi('app:user:export')")
    @Log(title = "小程序用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user) {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "小程序用户数据");
    }

    /**
     * 获取小程序用户详细信息
     */
    @ApiOperation("小程序用户详细信息")
    @PreAuthorize("@ss.hasPermi('app:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(userService.selectUserById(id));
    }

    /**
     * 新增小程序用户
     */
    @ApiOperation("新增小程序用户")
    @PreAuthorize("@ss.hasPermi('app:user:add')")
    @Log(title = "小程序用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody User user) {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改小程序用户
     */
    @ApiOperation("修改小程序用户")
    @PreAuthorize("@ss.hasPermi('app:user:edit')")
    @Log(title = "小程序用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user) {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除小程序用户
     */
    @ApiOperation("删除小程序用户")
    @PreAuthorize("@ss.hasPermi('app:user:remove')")
    @Log(title = "小程序用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(userService.deleteUserByIds(ids));
    }


    @PostMapping("/phoneLogin")
    @ApiOperation("手机号登录")
    public AjaxResult phoneLogin(@RequestBody(required = true) PhoneLoginDTO loginDTO) {
        return userService.loginByPhone(loginDTO);
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public Map<String, Object> register(@RequestBody Map<String, String> request) {
        String phone = request.get("phone");
        String password = request.get("password");
        String nickName = request.get("nickName");

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)) {
            return AjaxResult.error("手机号和密码不能为空");
        }

        try {
            userService.register(phone, password, nickName);
            return AjaxResult.success("注册成功");
        } catch (Exception e) {
            return AjaxResult.error("注册失败：系统内部异常！" );
        }

    }

    /**
     * 获取当前用户信息
     * <p>
     * 接口路径：/app/user/info
     * 请求方式：GET
     * 权限要求：已登录用户
     */
    @PreAuthorize("@ss.hasPermi('app:user:info')")
    @GetMapping("/info/{userId}")
    public AjaxResult getUserInfo(@PathVariable String userId) {
        UserInfoVO userInfo = userService.getCurrentUserInfo(Long.valueOf(userId));
        return AjaxResult.success(userInfo);
    }

    @PostMapping("/update")
    @ApiOperation("更新用户信息")
    @PreAuthorize("@ss.hasPermi('app:user:update')")
    public AjaxResult updateUserInfo(
            @RequestPart("nickName") String nickName,
            @RequestPart("gender") Integer gender,
            @RequestPart("address") String address,
            @RequestPart("nationality") String nationality,
            @RequestPart("avatarFile") MultipartFile avatarFile,
            @RequestParam("userId") Long userId) {

        return AjaxResult.success(userService.updateUserInfo(userId, nickName, gender, address, nationality, avatarFile));
    }

    @PutMapping("/bind")
    @ApiOperation("绑定手机号")
    @PreAuthorize("@ss.hasPermi('app:user:bind')")
    public AjaxResult bindPhone(@RequestBody PhoneLoginDTO loginDTO, @RequestParam("openid") String openid) {
        return userService.bindPhone(loginDTO, openid);
    }

    @PutMapping("/modifyPassword")
    @ApiOperation("修改密码")
    @PreAuthorize("@ss.hasPermi('app:user:modifyPassword')")
    public AjaxResult modifyPassword(@RequestParam("userId") Long userId,
                                     @RequestParam("oldPassword") String oldPassword,
                                     @RequestParam("newPassword") String newPassword) {
        return userService.modifyPassword(userId, oldPassword, newPassword);
    }




}
